﻿/*******************************
 * Library     : ShandaGames.UnionSNS.Common
 * Author      : Kestin
 * Description : Xml类型序列化辅助类
 * ****************************/

using System;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

namespace SGS.Utility
{
    /// <summary>
    /// Xml类型序列化辅助类
    /// 
    /// 为了保证特殊字符能被序列化，XmlWriterSettings.CheckCharacters始终为false
    /// </summary>
    public static class XmlSerializerHelper
    {
        /// <summary>
        /// 对象序列化到XML
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string Serialize(object obj)
        {
            
            if (obj == null)
            {
                return string.Empty;
            }
            XmlWriterSettings setting = new XmlWriterSettings();
            setting.Encoding = Encoding.UTF8;
            setting.Indent = true;
            setting.CheckCharacters = false;

            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(obj.GetType());
            
            MemoryStream stream = new MemoryStream();
            using (XmlWriter writer = XmlWriter.Create(stream, setting))
            {
                ser.Serialize(writer, obj);
            }

            stream.Position = 0;
            using (StreamReader sr = new StreamReader(stream))
            {
                return sr.ReadToEnd();
            }
        }
        
        public static T Deserialize<T>(string xmlString)
        {
            return Deserialize<T>(xmlString, Encoding.UTF8);
        }

        public static T Deserialize<T>(string xmlString, Encoding encoding)
        {
            return (T)Deserialize(xmlString, encoding, typeof(T));
        }

        public static object Deserialize(string xmlString, Encoding encoding, Type type)
        {
            if (string.IsNullOrEmpty(xmlString))
            {
                return null;
            }

            var xmlSerializer = new XmlSerializer(type);
            using (var ms = new MemoryStream())
            {
                var buffer = encoding.GetBytes(xmlString);
                ms.Write(buffer, 0, (int)buffer.Length);
                ms.Position = 0;

                var o = System.Xml.XmlReader.Create(ms, new System.Xml.XmlReaderSettings()
                {
                    CheckCharacters = false,
                });

                // return (T)xmlSerializer.Deserialize(ms);
                return xmlSerializer.Deserialize(o);
            }
        }

       
    }
}
